package org.wesc.boot.webapi.aspect;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.wesc.boot.common.annotation.ApiEndpoint;
import org.wesc.boot.secure.jwt.JwtUtil;
import org.wesc.boot.service.system.log.SysLogAdvanceService;

import java.lang.reflect.Method;

/**
 * API调用切面
 * @author Wesley
 * @date 2021/4/29
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class ApiEndpointAspect extends BaseAspect {

    private final SysLogAdvanceService logAdvanceService;

    @Pointcut("@annotation(org.wesc.boot.common.annotation.ApiEndpoint)")
    public void pointcut() {}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object result;
        Method targetMethod = resolveMethod(point);
        ApiEndpoint annotation = targetMethod.getAnnotation(ApiEndpoint.class);
        String operation = annotation.operation();
        long start = System.currentTimeMillis();
        result = point.proceed();
        if (StringUtils.isNotBlank(operation)) {
            RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) attributes;
            String ip = StringUtils.EMPTY;
            if (servletRequestAttributes != null) {
                ip = servletRequestAttributes.getRequest().getRemoteAddr();
            }
            String username = JwtUtil.getCurrentUserName();
            if (null != username) {
                logAdvanceService.saveLog(username, point, targetMethod, ip, operation, start);
            }
        }
        return result;
    }

}
